package com.ruoyi.factory.qylock.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.archive.domain.Archive;
import com.ruoyi.factory.archive.mapper.ArchiveMapper;
import com.ruoyi.factory.qylock.domain.IndividualTaxVO;
import com.ruoyi.factory.qylock.mapper.IndividualTaxMapper;
import com.ruoyi.factory.qylock.service.IndividualTaxService;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import com.ruoyi.factory.qylock.utils.UicodeBackslashU;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class IndividualTaxServiceImpl implements IndividualTaxService {

    protected final Logger logger = LoggerFactory.getLogger(IndividualTaxServiceImpl.class);

    @Autowired
    private IndividualTaxMapper individualTaxMapper;
    @Autowired
    private ArchiveMapper archiveMapper;

    /**
     * @author: LiuJiaji
     * @date: 2025/6/19 15:59
     * @description: TODO 离职个人所得税通知书 1.erp数据查询 2.数据整理 3.请求契约锁 4.契约锁签署状态更新
     * @param:
     * @return:
     **/
    @Override
    public void individualTaxesign(){
        // erp数据查询
        IndividualTaxVO paramindivo = new IndividualTaxVO();
        //设置时间
        Calendar instance = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = instance.getTime();
        String timee = sdf.format(time);
        instance.add(Calendar.MONTH,-1);
        Date time1 = instance.getTime();
        String times = sdf.format(time1);
        paramindivo.setCreateTimes(times);
        paramindivo.setCreateTimee(timee);
        List<IndividualTaxVO> individualTaxVOS = individualTaxMapper.selectIndividualtaxlist(paramindivo);
        for (IndividualTaxVO individualTaxVO : individualTaxVOS) {
            //流程id和模板id查询
            Archive archive = new Archive();
            archive.setTypeCode("dzqz");
            archive.setPcode(paramindivo.getPk_org());
            archive.setName("1001LZTZ1BZ01");
            List<Archive> archives1 = archiveMapper.selectArchiveList(archive);
            String flowID = "";
            String templateID = "";
            for (Archive archive1 : archives1) {
                if(archive1.getName().contains("1001LZTZ1BZ01")){
                    Archive archive2 = new Archive();
                    flowID = archive1.getCode();
                    archive2.setPcode(flowID);
                    List<Archive> archives2 = archiveMapper.selectArchiveList(archive2);
                    for (Archive archive3 : archives2) {
                        String name = archive3.getName();
                        String[] split = name.split("-");
                        if("01".equals(split[1])){
                            templateID = archive3.getCode();
                        }
                    }
                }
            }

            //请求数据整理
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("subject","个人所得税缴纳通知"+individualTaxVO.getApplyName());
            jsonObject1.put("categoryId",flowID);
            jsonObject1.put("tenantName","新乡市瑞丰新材料股份有限公司");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String format2 = sdf2.format(time);
            jsonObject1.put("sn",flowID+format2);

            JSONArray signatories = new JSONArray();
            JSONObject signatoriesa1 = new JSONObject();
            signatoriesa1.put("tenantType","PERSONAL");
            signatoriesa1.put("tenantName",individualTaxVO.getApplyName());
            signatoriesa1.put("serialNo","1");
            signatoriesa1.put("receiverName",individualTaxVO.getApplyName());
            String mobile = individualTaxVO.getMobile();
            if(mobile.contains("-")){
                String[] split = mobile.split("-");
                mobile = split[1];
            }
            signatoriesa1.put("contact",mobile);
            signatories.add(signatoriesa1);
            jsonObject1.put("signatories",signatories);

            JSONArray jsonArray = new JSONArray();
            jsonArray.add(templateID);
            jsonObject1.put("templates",jsonArray);

            JSONArray documentParams = new JSONArray();
            JSONObject qdrqn = new JSONObject();
            String applyDate = individualTaxVO.getApplyDate();
            if(StringUtils.isNotBlank(applyDate) && !"~".equals(applyDate)){
                String nian = applyDate.substring(0, 4);
                String yue = applyDate.substring(5, 7);
                String ri = applyDate.substring(8, 10);
                String nyr = nian+"年"+yue+"月"+ri+"日";
                qdrqn.put("name","申请日期");
                qdrqn.put("value",nyr);
                documentParams.add(qdrqn);
            }

            JSONObject lzrxm = new JSONObject();
            lzrxm.put("name","离职人姓名");
            lzrxm.put("value",individualTaxVO.getApplyName());
            documentParams.add(lzrxm);

            JSONObject sfzh = new JSONObject();
            sfzh.put("name","身份证号");
            sfzh.put("value",individualTaxVO.getCardId());
            documentParams.add(sfzh);

            JSONObject sjh = new JSONObject();
            sjh.put("name","手机号");
            sjh.put("value",individualTaxVO.getMobile());
            documentParams.add(sjh);

            JSONObject yjse = new JSONObject();
            yjse.put("name","应缴税额");
            yjse.put("value",individualTaxVO.getTaxmony());
            documentParams.add(yjse);
            jsonObject1.put("documentParams",documentParams);

            //请求契约锁
            String url = "/contract/createbycategory";
            logger.info("请求契约锁发起签章请求参数: "+jsonObject1.toString());
            String res2 = OkHttpUtils.okHttpPostqys(url, jsonObject1.toString());
            Date date = new Date();
            logger.info("请求契约锁发起签章返回结果时间"+date);
            String res3 = UicodeBackslashU.unicodeToCn(res2);
            logger.info("请求契约锁发起电子签约返参: "+res3);
            //处理返回结果
            JSONObject jsonObject = JSONObject.fromObject(res3);
            String code1 = jsonObject.optString("code");
            String message = jsonObject.optString("message");
            if("0".equals(code1) && "SUCCESS".equals(message)){
                //成功 更新状态
                String contractId = jsonObject.optString("contractId");
                individualTaxVO.setContractId(contractId);
                individualTaxVO.setEsignStatus("签署中");
                String pk_hi_stapply = individualTaxVO.getPk_hi_stapply();
                if(StringUtils.isNotBlank(pk_hi_stapply) && !"~".equals(pk_hi_stapply)){
                    int i = individualTaxMapper.updateIndividualTaxVO(individualTaxVO);
                }

            }

        }





//        List<Archive> archives = archiveMapper.selectArchiveList(archive);
//        for (IndividualTaxVO individualTaxVO : individualTaxVOS) {
//            Map<String, String> fandTid = getFandTid(type,laborConVO.getOrgid());
//            if(null != fandTid){
//                flowID=fandTid.get("flowID");
//                templateID=fandTid.get("templateID04");
//            }
//        }摆一桌 2000 2100 2300 2500 100 300 500 1000 800 500 2500+1500 +500 +1000 + 200
        //整理数据
        //传输
        //有单都下到其他人那薪资构成
    }


    public AjaxResult upStatus(Map<String,String> request){
        //根据文件id修改状态
        //解析数据
        JSONObject jsonObject = JSONObject.fromObject(request);
        logger.info("人力合同台账契约锁回调参数"+jsonObject.toString());
        String status = jsonObject.optString("status");

        //判断状态
        if("COMPLETE".equals(status)){
            String fileid = jsonObject.optString("contractId");
            IndividualTaxVO laborConVO = new IndividualTaxVO();
            laborConVO.setContractId(fileid);
            List<IndividualTaxVO> individualTaxVOS = individualTaxMapper.selectIndividualtaxlist(laborConVO);
            if(!individualTaxVOS.isEmpty()){
                laborConVO.setEsignStatus("已签署");
                individualTaxMapper.updateIndividualTaxVO(laborConVO);
            }
        }
        return new AjaxResult(200,"成功");
    }
}